package com.flybear.aqi.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * Handler implementation for the echo client.  It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {
    private Logger log = LoggerFactory.getLogger(getClass());
    private final ByteBuf firstMessage;

    /**
     * Creates a client-side handler.
     */
    public EchoClientHandler() {
        firstMessage = Unpooled.buffer(EchoClient.SIZE);
//        for (int i = 0; i < firstMessage.capacity(); i ++) {
//            firstMessage.writeByte((byte) i);
//        }

//        firstMessage.writeBytes(C1.getBytes(Charset.forName("UTF-8")));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(ctx.channel().localAddress().toString()+" channelActive");
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        log.info("收到服务端[ip:" + clientIp + "]连接");
        int num=10;
        for(int i=0;i<num;i++) {
            String C1 = "##1234QN=20160801085857223;ST=32;CN=2011;PW=123456;MN=010000A8900016F" +
                    "000169DC0;Flag=5;CP=&&DataTime=" + DateTime.now().toString("yyyyMMddHHmmss") + ";w01001-Rtd=7.1,w0100" +
                    "1-Flag=N;w01018-SampleTime=20160801070000,01018-Rtd=2.2,w01018-Flag=" +
                    "N,w01018-EFlag=A01;&&1C80;\r\n";

            ctx.writeAndFlush(C1);
        }
    }
//    String C2="QN=20160801085857223;ST=32;CN=3020;PW=123456;MN=010000A8900016F000169DC0;Flag=5;CP=&&DataTime=20160801085857;PolId=w01018;i13004-Info=168.0; i13005-Info =40&&\r\n";
    //上位机 返回数据应答
//    String AC2="QN=20160801085857223;ST=91;CN=9014;PW=123456;MN=010000A8900016F000169DC0;Flag=4;CP=&&&&\r\n";
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("client receive msg >>> "+msg);
//        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
       ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
